﻿using Newtonsoft.Json;
using Fortunate.Common.Extensions;
namespace Fortunate.ViewModel
{
    public class DesensitizationConvter : JsonConverter
    {
        //关闭反序列化
        public override bool CanRead => false;
        //开启自定义序列化
        public override bool CanWrite => true;
        public override bool CanConvert(Type objectType)
        {
            return true;
        }
        private readonly int StartLen;
        private readonly int SubLen;
        private readonly char SpecialChar;
        /// <summary>
        /// 默认前保留长度2，脱敏长度4，特殊字符为*
        /// </summary>
        public DesensitizationConvter()
        {
            StartLen = 2;
            SubLen = 4;
            SpecialChar = '*';
        }
        /// <summary>
        /// 根据传入的长度进行脱敏
        /// </summary>
        /// <param name="startLen">前保留长度</param>
        /// <param name="subLen">脱敏长度</param>
        public DesensitizationConvter(int startLen, int subLen) : this()
        {
            StartLen = startLen;
            SubLen = subLen;
        }
        /// <summary>
        /// 根据传入的长度及特殊字符进行脱敏
        /// </summary>
        /// <param name="startLen">前保留长度</param>
        /// <param name="subLen">脱敏长度</param>
        /// <param name="specialChar">替换的特殊字符</param>
        public DesensitizationConvter(int startLen, int subLen, char specialChar) : this(startLen, subLen)
        {
            SpecialChar = specialChar;
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (value != null)
            {
                //writer.WriteValue(value.ToString()?.ReplaceWithSpecialChar(StartLen, SubLen, SpecialChar));
                writer.WriteValue(value.ToString()?.SetSensitiveName());

            }
        }
    }
}
